/**
 * @ 从一个字符串里删除一个字符或一个字符串
 * @ 怎样删除一个字符串
 * @author	 wangshikun <wangshikun2010@gmail.com>
 * @copyright	(c) 2012 wangshikun <wangshikun2010@gmail.com>
 * @license	http://www.opensource.org/licenses/mit-license.php The MIT License
 * @package	default
 * @startpackage	default
 */

#include <stdio.h>
#include <cs50.h>
#include <string.h>

// 函数声明
void removeString(char text[], int start, int x);

// 主函数
int main(void) {
	char text[] = {"abcdefghijklmnopqrstuv wx yz"};
	int start, x;
	
	// 输入
	printf("\n母字符串：%s\n\n", text);
	printf("请输入要删除的字符串的开始下标：");
	scanf("%d", &start);
	printf("请输入要删除的字符串的个数：");
	scanf("%d", &x);

	// 调用函数
	//printf("%s", removeString(text, start, x));
	removeString(text, start, x);

	return 0;
}

// 删除字符串
void removeString(char text[], int start, int x) {

	// if delete from end
	if (start < 0) {
		start = strlen(text) + start - x;
	}

	// exit if user want to remove negative number of char
	if (x < 0) {
		fprintf(stderr, "Invalid parameter!\n");
		exit(1);
	}

	if (x > strlen(text) - start){
		x = strlen(text) - start;
	}

	printf("start=%d, count=%d\n", start, x);

	char *newString = malloc(sizeof(char) * (strlen(text) - x + 1));
	
	// copy old string to new string, skip deleted ones
	int j = 0;
	for (int i=0; i<strlen(text); i++) {
		if (i >= start && i < (start+x)) {
			// do not copy to newString
		} else {
			newString[j++] = text[i]; 
		}
	}

	newString[j] = '\0';

	printf("after remove: %s\n", newString);

	free(newString);
}

